package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.bridge.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:DishServiceImpl
 * @Author:泛微-boliu14
 * @Date:2023/11/6 21:38
 * @Description:菜品管理
 */
@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;


    @Autowired
    private DishFlavorMapper dishFlavorMapper;


    @Autowired
    private SetmealMapper setmealMapper;


    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品和对应的口味
     * @param dishDTO
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //向菜品表中插入一条数据
        dishMapper.insert(dish);

        //获取insert语句生成的主键值
        Long dishId = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            //向口味表插入N条数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }


    /**
     * 批量删除菜品
     *      * - 可以一次删除一个菜品，也可以批量删除菜品
     *      * - 起售中的菜品不能删除
     *      * - 被套餐关联的菜品不能删除
     *      * - 删除菜品后，关联的口味数据也需要删除掉
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品中是否有不能删除的数据---是否存在起售中的菜品
        Integer count = dishMapper.getMinimumQuantityByIds(ids, StatusConstant.ENABLE);
        if (count > 0){
            //当前菜品中有处于起售的，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }

        //判断当前菜品是否有不能删除的数据----是否存在关联套餐的菜品
        count = setmealDishMapper.getNumberAssociatedSetmealByIds(ids);

        //TODO 这种情况待套餐功能完成后才能测试
        if (count > 0 ){
            //当前菜品中有被套餐关联的，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品表中的菜品数据
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByDishIds(ids);



    }

    /**
     * 根据id查询菜品及菜品的口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);
        //根据菜品id查询菜品的口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }


    /**
     * 根据菜品id修改菜品信息和菜品的口味数据
     * @param dishDTO
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDTO dishDTO) {

        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //更新菜品信息
        dishMapper.update(dish);

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishDTO.getId());
            });

            //删除改菜品的所有口味数据
            dishFlavorMapper.deleteByDishId(dishDTO.getId());
            //向口味表插入N条新的口味数据
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据分类ID菜品信息
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> list(Long categoryId) {

        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishs = dishMapper.list(dish);

        return dishs;
    }


    /**
     * 修改菜品状态
     * 4.启售/停售
     *
     * 4.1 菜品停售，则包含菜品的套餐同时停售。
     *
     * 4.2 【启售/停售】，菜品被停售后，前台不展示
     *
     *      点【启售/停售】弹出确认弹窗，操作成功提示 操作成功，失败提示 操作失败。
     * @param id
     * @param status
     */
    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        //查询出所有包含该菜品的套餐信息
        List<SetmealDish> setmealDishList = setmealDishMapper.getSetmealDishByDishId(id);
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
       if (setmealDishList != null&&setmealDishList.size()>0&&status==StatusConstant.DISABLE){
            //如果有包含该菜品的套餐，把关联的所有套餐先停售
            for (SetmealDish setmealDish : setmealDishList) {
                Setmeal setmeal = new Setmeal();
                setmeal.setId(setmealDish.getSetmealId());
                setmeal.setStatus(status);
                setmealMapper.update(setmeal);
            }
        }
        dishMapper.update(dish);

    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
